package com.faxe.educar.ws.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.faxe.educar.ws.bo.UserBO;
import com.faxe.educar.ws.to.UserTO;
 
@Controller
public class ClientController {
	
	private UserBO userMgr;
	
	
	
	@RequestMapping(value="/save", method = RequestMethod.POST)
	public ModelAndView save(HttpServletRequest request,
			@RequestParam(required = true, value="name") String name,
			@RequestParam(required = true, value="email") String email,
			@RequestParam(required = true, value="password") String password,
			@RequestParam(required = true, value="confirmPassword") String confirmPassword,
			@RequestParam(required = false, value="address") String address,
			@RequestParam(required = false, value="country") String country,
			@RequestParam(required = false, value="state") String state,
			@RequestParam(required = false, value="city") String city,
			@RequestParam(required = false, value="neighbourhood") String neighbourhood,
			@RequestParam(required = false, value="age") String age,
			@RequestParam(required = false, value="phoneNumber") String phoneNumber,
			@RequestParam(required = false, value="cpf") String cpf){
				
		
		
		UserTO user = userMgr.getUserByEmail(email);
		
		if (user != null){
			request.setAttribute("saveError", true);
			return new ModelAndView("site/home");
		}
		user = new UserTO();
		
		user.setName(name);
		user.setEmail(email);
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		
		String hashedPassword = passwordEncoder.encode(password);
		user.setPassword(hashedPassword);
		
		
		
		user.setAuthority(UserTO.AUTH_TEACHER);
		
		userMgr.save(user);
		
		request.setAttribute("saveOK", true);
		return new ModelAndView("site/home");
	}
	
	@Autowired
	public void setUserBO(UserBO userBO){
		this.userMgr = userBO;
	}
	
	
}